<!-- 充值记录页面 -->
<template>
  <div>
    <div class="rechargeRecord-wrap">
      <div class="left-box" :class="{ fullWidth: selectRechargeOrderData ? false : true }">
        <div class="title-box">充值记录</div>
        <div class="search-content">
          <div class="datetimerange-type-box">
            <el-date-picker
              v-model="pageParam.betweenTime"
              type="datetimerange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="yyyy-MM-dd HH:mm:ss"
              @change="onSearch"
            >
            </el-date-picker>
            <!-- <div class="refund-type">
                <div class="desc">充值状态</div>
                <el-select
                  v-model="pageParam.pay_status"
                  @change="onSearch"
                  placeholder="请选择充值状态"
                  clearable
                >
                  <el-option
                    v-for="item in payStatusOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  >
                  </el-option>
                </el-select>
              </div> -->
            <div
              class="refund-type"
              style="display: flex; align-items: center; gap: 10px; white-space: nowrap"
            >
              <div class="desc">充值状态</div>
              <el-select
                v-model="pageParam.pay_status"
                @change="onSearch"
                placeholder="请选择充值状态"
                clearable
                style="width: 220px"
              >
                <el-option
                  v-for="item in payStatusOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select>
            </div>
          </div>
          <div class="search-input-button">
            <div class="search-input-box">
              <img class="search-icon" src="@/assets/images/home/search-icon.png" alt="" />
              <input
                class="input"
                v-model="pageParam.search"
                type="text"
                placeholder="搜索会员卡号/会员姓名/操作人"
                @keyup.enter="onSearch"
                @input="onSearch"
              />
            </div>
            <!-- <el-button @click.stop="onSearch">搜索</el-button> -->
          </div>
        </div>
        <div class="table-box">
          <el-table
            ref="table"
            :data="tableDataList"
            style="width: 100%"
            border
            v-loading="tableLoading"
            element-loading-text="加载中..."
            @row-click="singleElection"
          >
            <el-table-column label="" width="30">
              <template #default="scope">
                <el-radio
                  class="radio"
                  v-model="orderId"
                  :label="scope.row.order_id"
                  :disabled="scope.row.pay_status == 10"
                >
                  <span> </span
                ></el-radio>
              </template>
            </el-table-column>
            <el-table-column align="center" prop="order_id" label="ID" show-overflow-tooltip>
            </el-table-column>
            <el-table-column align="center" prop="order_no" label="会员卡号" show-overflow-tooltip>
            </el-table-column>
            <el-table-column align="center" label="会员姓名" show-overflow-tooltip>
              <template #default="{ row }">
                <span>{{ row.user.real_name }}</span>
              </template>
            </el-table-column>
            <el-table-column
              align="center"
              prop="store_user.real_name"
              label="收银员"
              show-overflow-tooltip
            ></el-table-column>
            <el-table-column align="center" prop="pay_price" label="充值金额" show-overflow-tooltip>
              <template #default="{ row }">
                {{ formatMoney(row.pay_price) }}
              </template>
            </el-table-column>
            <el-table-column
              align="center"
              prop="pay_status"
              label="充值状态"
              show-overflow-tooltip
            >
              <template #default="{ row }">
                <el-tag
                  :type="getPayStatusTagType(row.pay_status)"
                  :effect="getPayStatusTagEffect(row.pay_status)"
                >
                  {{ payStatusEnum[row.pay_status] }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column
              align="center"
              prop="create_time"
              label="充值时间"
              show-overflow-tooltip
            >
            </el-table-column>
          </el-table>
        </div>
        <div class="dialog-pagination">
          <!-- 分页器 -->
          <Pagination
            v-show="total > 0"
            :total="total"
            v-model:page="pageParam.page"
            v-model:limit="pageParam.limit"
            @pagination="handlePagination"
            :pageSizes="[15, 45, 75, 100]"
          />
        </div>
        <div class="table-bottom-box">
          <div class="desc"></div>
          <div class="btn-box">
            <div class="cancel-btn" @click="handleOpenRechargeRevoke">撤销充值</div>
            <div
              class="print-btn"
              :class="{ loading: printLoading, disabled: printLoading }"
              @click="printOrder"
            >
              {{ printLoading ? '打印中...' : '打印' }}
            </div>
            <div class="back-btn" @click="handleBack">返回</div>
          </div>
        </div>
      </div>
      <div class="right-box">
        <!-- 餐厅充值单组件 -->
        <RestaurantRechargeBill :selectedOrderData="selectedRechargeOrderData" />
      </div>
    </div>
  </div>
</template>
<script setup>
import { ref, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import RestaurantRechargeBill from './components/RestaurantRechargeBill.vue'
import messageTips from '@/components/messageTips/index'
import Pagination from '@/components/Pagination/Index.vue'
// 引入会员接口api
import * as memberApi from '@/api/member'
import { debounce, throttle } from '@/utils/toolsValidate'
//   import { printOrder } from '@/api/printer'
import { printerReprint } from '@/api/common.ts'
import { rechargeOrderDetailTicket } from '@/api/member'

// 路由
const router = useRouter()

// 响应式数据
const datetimerangeList = ref([])
const tableDataList = ref([])
const total = ref(0)
const payStatusEnum = ref({
  10: '待支付',
  20: '已支付',
  30: '已退款',
  40: '支付中'
})
const payStatusOptions = ref([
  { value: 0, label: '全部' },
  { value: 10, label: '待支付' },
  { value: 40, label: '支付中' },
  { value: 20, label: '已支付' },
  { value: 30, label: '已退款' }
])
const pageParam = ref({
  search: '',
  pay_status: 0,
  betweenTime: [],
  page: 1,
  limit: 15
})
const rechangeType = ref('')
const searchKeyword = ref('')
const orderId = ref('')
const payMoneyStatus = ref('')
const selectedRechargeOrderData = ref(null)
const tableLoading = ref(false)
const printLoading = ref(false)

// 计算属性
const selectRechargeOrderData = computed(() => selectedRechargeOrderData.value)

// 生命周期钩子
onMounted(() => {
  selectedRechargeOrderData.value = null
  getRechargeRocordList()
})

// 返回上一页
const handleBack = () => {
  router.go(-1)
}

// 搜索提交事件
const onSearch = debounce(() => {
  pageParam.value.page = 1
  getRechargeRocordList()
}, 300)

// 分页事件处理
const handlePagination = paginationData => {
  pageParam.value.page = paginationData.page
  pageParam.value.limit = paginationData.limit
  getRechargeRocordList()
}

// 获取支付状态标签类型
const getPayStatusTagType = status => {
  switch (status) {
    case 10: // 待支付
      return 'warning'
    case 20: // 已支付
      return 'success'
    case 30: // 已退款
      return 'danger'
    case 40: // 支付中
      return 'info'
    default:
      return 'info'
  }
}

// 获取支付状态标签效果
const getPayStatusTagEffect = status => {
  switch (status) {
    case 10: // 待支付
      return 'light'
    case 20: // 已支付
      return 'dark'
    case 30: // 已退款
      return 'light'
    case 40: // 支付中
      return 'light'
    default:
      return 'light'
  }
}

// 格式化金额，添加3位逗号分割
const formatMoney = amount => {
  if (!amount && amount !== 0) return '0'
  const num = parseFloat(amount)
  if (isNaN(num)) return '0'
  return num.toLocaleString('zh-CN', {
    minimumFractionDigits: 2,
    maximumFractionDigits: 2
  })
}

// 获取充值记录列表
const getRechargeRocordList = () => {
  tableLoading.value = true
  memberApi
    .fetchRechargeList(pageParam.value)
    .then(res => {
      if (res.status === 200) {
        total.value = res?.data?.list?.total || 0
        tableDataList.value = res?.data?.list?.data || []
      }
    })
    .finally(() => {
      tableLoading.value = false
    })
}

// 选中当前行
const singleElection = row => {
  // 如果是未支付状态，不允许选中
  if (row.pay_status == 10) {
    return
  }
  selectedRechargeOrderData.value = row
  orderId.value = row.order_id
  payMoneyStatus.value = Number(row.pay_status)
}

// 打开撤销充值的弹窗
const handleOpenRechargeRevoke = async () => {
  if (!orderId.value) {
    ElMessage.warning('请先选择订单')
    return
  }
  if (payMoneyStatus.value !== 20) {
    ElMessage.warning('当前订单未支付，不能执行此操作')
    return
  }

  const selectedOrder = selectedRechargeOrderData.value
  if (!selectedOrder) {
    ElMessage.warning('请先选择订单')
    return
  }

  const messageInstance = await messageTips.message(
    {
      title: '撤销充值',
      content: `确定要对【${selectedOrder.user?.real_name || '未知用户'}】撤销【${selectedOrder.pay_price}】充值吗？<br/>撤销后此会员将减少此次充值金额`,
      isOnCancel: true,
      onCancelText: '取消',
      onSumbitText: '确定'
    },
    async () => {
      try {
        messageInstance.setLoading(true)
        const res = await memberApi.rechargeRevoke({ orderId: orderId.value })
        if (res.status === 200) {
          ElMessage.success('撤销成功')
          getRechargeRocordList()
        }
      } catch (error) {
        ElMessage.error('撤销失败')
        console.error('撤销充值失败:', error)
      } finally {
        messageInstance.setLoading(false)
        messageInstance.close && messageInstance.close()
      }
    },
    async () => {
      // 取消操作
      console.log('用户取消撤销充值')
    }
  )
}

// 打印订单
const printOrder = () => {
  if (!selectRechargeOrderData.value) {
    ElMessage.warning('请先选择订单')
    return
  }
  if (printLoading.value) {
    return // 防止重复点击
  }

  printLoading.value = true
  rechargeOrderDetailTicket({
    order_id: selectRechargeOrderData.value.order_id
  })
    .then(res => {
      if (res.status === 200) {
        printerReprint({
          ticket_id: res.data.detail.ticket_id
        })
          .then(res => {
            ElMessage.success('推送打印成功')
          })
          .catch(error => {
            ElMessage.error('打印失败')
            console.error('打印失败:', error)
          })
      }
    })
    .catch(error => {
      ElMessage.error('获取打印数据失败')
      console.error('获取打印数据失败:', error)
    })
    .finally(() => {
      printLoading.value = false
    })
}
</script>
<style lang="scss" scoped>
::v-deep {
  .el-table {
    border-radius: 12px;
    height: 600px;
  }
  .el-table__body-wrapper {
    height: 600px;
    overflow-y: auto;
  }
  //滚动条整体的大小
  .el-table__body-wrapper::-webkit-scrollbar {
    width: 6px !important;
    height: 0 !important;
  }
  //滚动条里滑动的滑块
  .el-table__body-wrapper::-webkit-scrollbar-thumb {
    height: 200px !important;
    background: #d2d2d2 !important;
    border-radius: 3px !important;
  }
  //滚动条底层样式
  .el-table__body-wrapper::-webkit-scrollbar-track {
    display: none !important;
  }
  .el-table th.el-table__cell {
    background: #a85b62;
    color: #fff !important;
  }
  .el-input__inner {
    border-radius: 12px;
  }
  .el-button {
    color: #fff;
    background-color: #7b0a03;
    border-color: #7b0a03;
    height: 46px;
    border-radius: 12px;
    margin-left: 20px;
  }
  .el-radio__input.is-checked .el-radio__inner {
    border-color: #7c0a03;
    background: #7c0a03;
  }
}
.fullWidth {
  width: 1600px !important;
  transition: all 1s !important;
}
.rechargeRecord-wrap {
  display: flex;
  align-items: flex-start;

  .left-box {
    box-sizing: border-box;
    width: 1284px;
    height: 986px;
    background: #ffffff;
    border-radius: 20px;
    box-shadow: 3px 0px 24px 0px rgba(0, 0, 0, 0.16);
    transition: all 1s !important;
    .title-box {
      height: 88px;
      line-height: 88px;
      background: #f4f4f4;
      border-radius: 20px 20px 0px 0px;
      font-size: 20px;
      font-family:
        PingFang SC,
        PingFang SC-Bold;
      font-weight: 700;
      text-align: center;
      color: #333333;
    }

    .search-content {
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding: 20px 30px;
      box-shadow: 0px 3px 6px 0px rgba(0, 0, 0, 0.04);

      .datetimerange-type-box {
        display: flex;
        align-items: center;

        .refund-type {
          display: flex;
          align-items: center;
          margin-left: 20px;

          .desc {
            font-size: 16px;
            font-family:
              PingFang SC,
              PingFang SC-Regular;
            font-weight: 400;
            text-align: left;
            color: #333333;
            margin-right: 20px;
          }
        }
      }
      .search-input-button {
        display: flex;
        align-items: center;
        .search-input-box {
          width: 300px;
          height: 46px;
          border: 1px solid #d2d2d2;
          border-radius: 25px;
          box-sizing: border-box;
          display: flex;
          align-items: center;
          padding-left: 20px;
          .search-icon {
            flex-shrink: 0;
            width: 24px;
            height: 24px;
          }

          .input {
            border: none;
            outline: none;
            width: 230px;
            font-size: 16px;
            font-family:
              PingFang SC,
              PingFang SC-Regular;
            font-weight: 400;
            text-align: left;
            color: #333;
            margin-left: 10px;
          }
          .search-btn {
            height: 46px;
            background: #7b0a03;
            border: none;
            border-radius: 10px;
            margin-left: 70px;
          }
        }
      }
    }

    .table-box {
      width: 100%;
      box-sizing: border-box;
      padding-left: 20px;
      padding-top: 20px;
      padding-right: 20px;
    }

    .dialog-pagination {
      display: flex;
      justify-content: center;
      margin-top: 20px;
    }
    .table-bottom-box {
      padding: 0 30px 0 60px;
      display: flex;
      align-items: center;
      justify-content: space-between;
      margin-top: 20px;
      .desc {
        font-size: 14px;
        font-family:
          PingFang SC,
          PingFang SC-Regular;
        font-weight: 400;
        text-align: left;
        color: #333333;
      }

      .btn-box {
        display: flex;
        align-items: center;

        .cancel-btn {
          width: 156px;
          height: 52px;
          line-height: 52px;
          background: #ffffff;
          border: 1px solid #333333;
          border-radius: 12px;
          font-size: 18px;
          font-family:
            PingFang SC,
            PingFang SC-Regular;
          font-weight: 400;
          text-align: center;
          color: #333333;
          cursor: pointer;
        }

        .back-btn {
          width: 120px;
          height: 52px;
          line-height: 52px;
          background: #ffffff;
          border: 1px solid #333333;
          border-radius: 12px;
          font-size: 18px;
          font-family:
            PingFang SC,
            PingFang SC-Regular;
          font-weight: 400;
          text-align: center;
          color: #333333;
          cursor: pointer;
          margin-left: 40px;
        }

        .print-btn {
          width: 120px;
          height: 52px;
          line-height: 52px;
          background: #ffffff;
          border: 1px solid #333333;
          border-radius: 12px;
          font-size: 18px;
          font-family:
            PingFang SC,
            PingFang SC-Regular;
          font-weight: 400;
          text-align: center;
          color: #333333;
          cursor: pointer;
          margin-left: 40px;
          transition: all 0.3s ease;

          &.loading,
          &.disabled {
            background: #f5f5f5;
            border-color: #cccccc;
            color: #999999;
            cursor: not-allowed;
          }
        }

        .cancel-btn:hover,
        .print-btn:hover,
        .back-btn:hover {
          color: #7c0a03;
          border-color: #7c0a03;
        }
      }
    }
  }

  .right-box {
    margin-left: 30px;
  }
}
</style>
